package blog.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import blog.entity.Article;
import blog.entity.Comment;
import blog.entity.User;
import blog.service.ArticleService;
import blog.service.CommentService;
import blog.service.UserService;

@Controller @RequestMapping("/user")
public class UserController {
	@Resource(name="userServiceImpl")
	private UserService  userService;
	
	@Resource
	private ArticleService articleService;
	
	@Resource
	private CommentService commentService;
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request) {
		String str=request.getParameter("userName");
		String password=request.getParameter("userPass");
		
		User user =userService.getUserByNameOrEmail(str);
		
		if(user!=null) {
			if(password.equals(user.getUserPass())) {
				request.getSession().setAttribute("session_user", user); 
				//查询最近的前5条文章
				List<Article> articleList=	articleService.listRecentArticle(5);
				request.setAttribute("articleList", articleList);
				
				//查询最近的前5条评论
				List<Comment>commentList=commentService.listRecentComment(5);
				request.setAttribute("commentList", commentList);
				
				return "index"; 
			}
			else {
				request.setAttribute("msg", "密码错误");
				return "login";
			}
		}
		else {
			request.setAttribute("msg", "账号错误");
			return "login";
		}
		
		
}
	
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String gotoAddPage() {
		
		return "User/user-add";
	}
	
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public String add(User user,MultipartFile photo) throws IOException {
		
		user.setUserRegisterTime(new Date());
		user.setUserPhoto(photo.getBytes());
		userService.add(user);
		
		return "forward:/user";
	}
	
	@RequestMapping("")
	public String  listUser(ModelMap m) {
		
		List<User> userList = userService.ListUser();
		m.put("userList", userList);
		return "User/user-list";
	}
	
	@RequestMapping("/photo/{userId}")
	public void getPhoto(@PathVariable("userId") Integer userId, HttpServletResponse response ) throws IOException {
		User  user=userService.getUserById(userId);
		
		response.setContentType("image/jpg");
		ServletOutputStream outStream =response.getOutputStream();
		outStream.write(user.getUserPhoto());
		
		outStream.flush();
	}

}
